﻿using System;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using Blazing.BusinessObjects.Assets;
using Blazing.WebFacade;
using Blazing.UI.Cms.Admin.Classes;
using System.IO;
using Blazing.Web.Util;

namespace Blazing.UI.Cms.Admin
{
    public partial class ManageAssets : SiteBasePage
    {
        private const string ROOT_PATH = "~/files/";

        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PopulateTree();
            }
            if (TreeViewDirectories.SelectedValue != "")
            {
                LabelDirectory.Text = "Assets in " + TreeViewDirectories.SelectedValue;
                AssetUpload.Enabled = true;
            }
            else
            {
                AssetUpload.Enabled = false;
            }
        }

        protected void PopulateTree()
        {
            DirectoryInfo rootFolder = new DirectoryInfo(Server.MapPath(ROOT_PATH));
            TreeNode root = null;            
            root = AddNodeAndDescendants(rootFolder, null);            
            TreeViewDirectories.Nodes.Clear();
            TreeViewDirectories.Nodes.Add(root);
            if (TreeViewDirectories.SelectedValue == "" && TreeViewDirectories.Nodes.Count > 0)
                TreeViewDirectories.Nodes[0].Select();
            TreeViewDirectories.ExpandAll();
        }

        protected TreeNode AddNodeAndDescendants(DirectoryInfo folder, TreeNode parentNode)
        {
            //Create the path for this level
            string virtualFolderPath;
            if (parentNode == null)
                virtualFolderPath = ROOT_PATH;
            else
                virtualFolderPath = parentNode.Value + folder.Name + "/";

            TreeNode node = new TreeNode(folder.Name, virtualFolderPath);

            //Recurse through children    
            if (folder.Exists)
            {
                DirectoryInfo[] subFolders = folder.GetDirectories();
                foreach (DirectoryInfo subFolder in subFolders)
                {
                    if (!subFolder.Name.StartsWith("_")) //consider '_' hidden
                    {
                        TreeNode child = AddNodeAndDescendants(subFolder, node);
                        node.ChildNodes.Add(child);
                    }
                }
            }
            
            return node;
        }

        protected void TreeViewDirectories_SelectedNodeChanged(object sender, EventArgs e)
        {
            if (TreeViewDirectories.SelectedValue != "")
                LabelDirectory.Text = "Images in " + TreeViewDirectories.SelectedValue;

            new AssetController().GenerateAssetsFromFiles(TreeViewDirectories.SelectedValue);

            ListView1.DataBind();
        }

        protected void DataSource_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            e.InputParameters["path"] = TreeViewDirectories.SelectedValue;
        }

        protected void ButtonCreateDirectory_Click(object sender, EventArgs e)
        {
            try
            {
                Directory.CreateDirectory(MapPath(TreeViewDirectories.SelectedValue) + TextBoxDirectoryName.Text);
                PopulateTree();
            }
            catch (Exception ex)
            {
                LabelMessage.Text = "Create Directory Failed: " + ex.Message;
            }
        }

        protected void LinkButtonDeleteDirectory_Click(object sender, EventArgs e)
        {
            try
            {
                Directory.Delete(MapPath(TreeViewDirectories.SelectedValue));
                PopulateTree();
                if (TreeViewDirectories.SelectedValue != "")
                    LabelMessage.Text = "Images in " + TreeViewDirectories.SelectedValue;
            }
            catch (Exception ex)
            {
                LabelMessage.Text = "Delete Directory Failed: " + ex.Message;
            }
        }
        
        protected void UploadButton_Click(object sender, EventArgs e)
        {
            Upload_Click(sender, new FileCollectionEventArgs(this.Request));
        }

        private void Upload_Click(object sender, FileCollectionEventArgs e)
        {
            if (AssetUpload.HasFile)
            {
                AssetController assetCon = new AssetController();
                if (!assetCon.CheckFileType(AssetUpload.PostedFile.FileName))
                {
                    LabelMessage.Text = "Selected file was not a valid image (jpg, jpeg, gif, png).";
                    return;
                }

                LabelMessage.Text = "Files Uploaded: " + Environment.NewLine;

                //Get asset type
                IList<AssetType> assetTypes = assetCon.GetAssetTypes();
                if (assetTypes.Count > 0)
                {
                    //Save the file
                    string fileName = System.IO.Path.GetFileName(AssetUpload.PostedFile.FileName);
                    AssetUpload.SaveAs(Server.MapPath(TreeViewDirectories.SelectedValue + fileName));

                    //Create the asset
                    Asset asset = new Asset();
                    asset.Description = TreeViewDirectories.SelectedValue + fileName;
                    asset.FileName = fileName;
                    asset.FilePath = TreeViewDirectories.SelectedValue;
                    asset.Name = fileName;
                    AssetType aType = assetTypes[0];
                    asset.AssetType = aType;
                    assetCon.NewAsset(asset);
                    LabelMessage.Text += AssetUpload.FileName + Environment.NewLine;
                }
                else
                {
                    LabelMessage.Text = "You must define asset types before you can load assets.";
                }
            }
            else
            {
                LabelMessage.Text = "No File Uploaded.";
            }

            odsAssets.Select();
            ListView1.DataBind();
        }

        bool CheckFileType(string fileName)
        {
            string ext = Path.GetExtension(fileName);
            switch (ext.ToLower())
            {
                case ".gif":
                case ".png":
                case ".jpg":
                case ".jpeg":
                    return true;
                default:
                    return false;
            }
        }

        protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            if (e.CommandName == "Cancel")
            {
                ListView1.SelectedIndex = -1;
            }
            else if (e.CommandName == "Thumb")
            {
                int id = int.Parse(ListView1.DataKeys[ListView1.EditIndex].Values["ID"].ToString());
                Asset asset = Asset.Load(id);
                string file = Server.MapPath(asset.FilePath + asset.FileName);

                var widthCtrl = e.Item.FindControl("txtWidth") as TextBox;
                var heightCtrl = e.Item.FindControl("txtHeight") as TextBox;

                ImageResize thumb = new ImageResize()
                {
                    File = System.Drawing.Image.FromFile(file),
                    Height = int.Parse(heightCtrl.Text),
                    Width = int.Parse(widthCtrl.Text),
                    PreserveAspectRatio = true
                };
                System.Drawing.Image imgtemp = thumb.GetThumbnail();

                FileInfo fileTo = new FileInfo(file);

                string newFilePath = Path.Combine(fileTo.DirectoryName, Path.GetFileNameWithoutExtension(file) + string.Format("_{0}x{1}.jpg", thumb.Width, thumb.Height));
                var fileToStream = File.OpenWrite(newFilePath);
                imgtemp.Save(fileToStream, System.Drawing.Imaging.ImageFormat.Jpeg);

                //AssetController newAssetController = new AssetController();
                //Asset newAsset = new Asset();
                //newAsset.Description = "Thumbnail";
                //newAsset.FileName = Path.GetFileName(newFilePath);
                //newAsset.FilePath = TreeViewDirectories.SelectedValue;
                //newAsset.Name = Path.GetFileName(newFilePath); ;
                //asset.AssetType = newAssetController.GetAssetTypes()[0];
                //newAssetController.NewAsset(asset);
            }
        }
    }
}
